package com.hpjpw.idoapp.service;

import com.hpjpw.ido.domain.Area;
import com.hpjpw.ido.domain.Guard;
import com.hpjpw.ido.domain.Student;
import com.hpjpw.ido.domain.Teacher;
import com.hpjpw.ido.service.IAreaService;
import com.hpjpw.ido.service.IGuardService;
import com.hpjpw.ido.service.IStudentService;
import com.hpjpw.ido.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: ruoyi
 * @BelongsPackage: com.hpjpw.idoapp.service
 * @Author: hpj
 * @CreateTime: 2021-01-05 21:21
 * @Description: 聊天模块Service
 */
@Service
public class IDoCommunicationService {
    @Autowired
    IAreaService areaService;
    @Autowired
    ITeacherService teacherService;
    @Autowired
    IStudentService studentService;
    @Autowired
    IGuardService guardService;

    public int deleteGuard(String grade) {
        int num = 0;
        Student student_q = new Student();
        student_q.setGrade(grade);
        List<Student> students = studentService.selectStudentList(student_q);
        for (Student student : students) {
            num += guardService.deleteGuardByUserId(student.getUserId());
        }
        return num;
    }

    public int generateGuard(String grade) {
        List<Area> areas = areaService.selectAreaList(new Area());
        int num = 0;
        for (Area area : areas) {
            Long areaId = area.getId();
            Student student_q = new Student();
            student_q.setAreaId(areaId);
            student_q.setGrade(grade);
            List<Teacher> teachers = teacherService.selectTeacherByAreaId(areaId);
            List<Student> students = studentService.selectStudentList(student_q);
            ArrayList<Long> userIDList = new ArrayList<>();
            for (Teacher teacher : teachers) {
                userIDList.add(teacher.getUserId());
            }
            for (Student student : students) {
                userIDList.add(student.getUserId());
            }
            Collections.shuffle(userIDList);
            int size = userIDList.size();
            num += size;
            for (int i = 0; i < size; i++) {
                Guard guard = new Guard();
                if (i == size - 1) {
                    guard.setProtectedId(userIDList.get(0));
                } else {
                    guard.setProtectedId(userIDList.get(i + 1));
                }
                guard.setGuardianId(userIDList.get(i));
                guard.setTime(new Date());
                guardService.insertGuard(guard);
            }

        }
        return num;
    }
}
